package com.cskaoyan.gateway.controller.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.pay.PayCoreService;
import com.mall.pay.constants.PayReturnCodeEnum;
import com.mall.pay.dto.PaymentRequest;
import com.mall.pay.dto.alipay.AlipayQueryRetResponse;
import com.mall.pay.dto.alipay.AlipaymentResponse;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;

/**
 * @Description: 支付模块
 * @Author: 徐能雄
 * @Date: 2021/10/5 16:55
 */
@RestController
@RequestMapping("/cashier")
public class PayController {

    @Reference(timeout = 30000, check = false)
    PayCoreService payCoreService;

    /**
     * 1、获取支付二维码
     */
    @PostMapping("/pay")
    public ResponseData aliPay(@RequestBody Map<String, String> map, HttpServletRequest request){

        String nickName = map.get("nickName");
        String money = map.get("money");
        String info = map.get("info");
        String orderId = map.get("orderId");
        String payType = map.get("payType");

        String userInfo = (String)request.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        Long uid = object.getLong("uid");

        PaymentRequest paymentRequest = new PaymentRequest();
        paymentRequest.setUserId(uid);
        paymentRequest.setTradeNo(orderId);
        paymentRequest.setTotalFee(new BigDecimal(money));
        paymentRequest.setOrderFee(new BigDecimal(money));
        paymentRequest.setSubject(info);
        paymentRequest.setPayChannel(payType);
        AlipaymentResponse response = payCoreService.aliPay(paymentRequest);
        //成功获取二维码
        if (PayReturnCodeEnum.SUCCESS.getCode().equals(response.getCode())){
            String qrCode = response.getQrCode();
            String codeUrl = "http://127.0.0.1:8080/image/" + qrCode;
            //String codeUrl = "http://192.168.8.35:8080/image/" + qrCode;
            return new ResponseUtil<>().setData(codeUrl);
        }else {
            //获取二维码异常
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
    }

    /**
     * 2、查询支付状态
     */
    @GetMapping("/queryStatus")
    public ResponseData queryAlipayRet(String orderId){
        PaymentRequest paymentRequest = new PaymentRequest();
        paymentRequest.setTradeNo(orderId);
        AlipayQueryRetResponse response = payCoreService.queryAlipayRet(paymentRequest);
        if (PayReturnCodeEnum.SUCCESS.getCode().equals(response.getCode())){
            return new ResponseUtil<>().setData(response.getMsg());
        }else {
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
    }
}
